<?php
namespace app\job;

use think\facade\Queue;
use think\facade\Db;
use think\exception\ValidateException;
use think\queue\Job;

class JobLive
{
    // 课程学习明细
    public function task1(Job $job, array $data)
    {

        $isJobDone = $this->doRecordJobTask1($data);

        if ($isJobDone['code'] == 0) {

            $job->delete();

            // 1.当前任务由哪个类来负责处理
            // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
            $jobHandlerClassNameTask1 = 'app\job\JobLive@task1';

            // 2.当任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueNameTask1 = "LiveRecordJobQueueTask1";


            // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
            $jobData = ['ts' => $isJobDone['ts'], 'download_id' => $isJobDone['download_id'], 'page' => $isJobDone['page'], 'start' => $isJobDone['start'], 'end' => $isJobDone['end']];

            // 4.将该任务推送到消息列表，等待对应的消费者去执行
            // 入队列，later延迟执行，单位秒，push立即执行
            Queue::push($jobHandlerClassNameTask1, $jobData, $jobQueueNameTask1);

        } elseif($isJobDone['code'] == 1) {
            $job->delete();
            Db::name('document')->where('id', '=', $data['download_id'])->update(['url' => '/csv/live/LiveRecord-'.date('YmdHis', $data['ts']).'.csv', 'complete_time'=>time()]);
            Db::name('temporary_members')->where('type', '=', 'LiveRecordJobQueue')->delete();
        } else {
            if ($job->attempts() > 3){
                $job->delete();
            }

        }

    }


    /**
     * 根据消息中的数据进行实际的业务处理...
     * @param array $data
     * @return bool
     */
    protected function doRecordJobTask1(array $data)
    {
        $date = date('YmdHis', $data['ts']);
        $file_path = root_path() . "/public/csv/live/LiveRecord-".$date.".csv";


        if (!file_exists($file_path)) {
            $fp = fopen($file_path,'a');

            //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));

            //添加导出标题
            fputcsv($fp, ['工号', '姓名', 'Division', '部门', '课程标题', '学习时长(s)']);
        } else {
            $fp = fopen($file_path,'a');

            //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
        }

        $members = Db::name('temporary_members')
            ->where('type', '=', 'LiveRecordJobQueue')
            ->field('members_id, name, userid, openid, department_name, division')
            ->order('id', 'asc')
            ->page($data['page'], 10)
            ->select()
            ->toArray();

        $where = [];
        if (!empty($data['start']) && !empty($data['end'])) {
            $where[] = ['a.date', '>=', date('Ymd', strtotime($data['start']))];
            $where[] = ['a.date', '<=', date('Ymd', strtotime($data['end']))];
        }

        if ($members) {
            foreach($members as &$v) {
                $inf = $v;
                $count = mb_strlen($inf['userid']);
                if ($count == 6) {
                    if (is_numeric($inf['userid'])) {
                        $userid = "'00".$inf['userid'];
                    } else {
                        $userid = $inf['userid'];
                    }
                } else {
                    $userid = $inf['userid'];
                }

                $dat = Db::table('o_live_log')
                    ->alias('a')
                    ->join('o_live b', 'b.id=a.live_id', 'left')
                    ->where('a.userid', '=', $inf['userid'])
                    ->where($where)
                    ->field('SUM(a.time) as duration, b.title')
                    ->group('a.live_id')
                    ->select()
                    ->toArray();

                if (!empty($dat)) {
                    foreach ($dat as &$vo) {
                        $array = [
                            $userid,
                            $inf['name'],
                            $inf['division'],
                            $inf['department_name'],
                            $vo['title'],
                            $vo['duration'],
                        ];

                        fputcsv($fp, $array);
                    }
                }
            }
            return ['code' => 0, 'ts' => $data['ts'], 'download_id' => $data['download_id'], 'page' => ($data['page'] + 1), 'start' => $data['start'], 'end' => $data['end']];

        } else {

            return ['code' => 1];
        }
    }



    // 员工学习明细
    public function task2(Job $job, array $data)
    {

        $isJobDone = $this->doRecordJobTask2($data);

        if ($isJobDone['code'] == 0) {

            $job->delete();

            // 1.当前任务由哪个类来负责处理
            // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
            $jobHandlerClassNameTask2 = 'app\job\JobLive@task2';

            // 2.当任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueNameTask2 = "LiveUserRecordJobQueueTask2";


            // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
            $jobData = ['ts' => $isJobDone['ts'], 'download_id' => $isJobDone['download_id'], 'page' => $isJobDone['page'], 'start' => $isJobDone['start'], 'end' => $isJobDone['end']];

            // 4.将该任务推送到消息列表，等待对应的消费者去执行
            // 入队列，later延迟执行，单位秒，push立即执行
            Queue::push($jobHandlerClassNameTask2, $jobData, $jobQueueNameTask2);

        } elseif($isJobDone['code'] == 1) {
            $job->delete();
            Db::name('document')->where('id', '=', $data['download_id'])->update(['url' => '/csv/live/LiveUserRecord-'.date('YmdHis', $data['ts']).'.csv', 'complete_time'=>time()]);
            Db::name('temporary_members')->where('type', '=', 'LiveUserRecordJobQueue')->delete();
        } else {
            if ($job->attempts() > 3){
                $job->delete();
            }

        }

    }


    /**
     * 根据消息中的数据进行实际的业务处理...
     * @param array $data
     * @return bool
     */
    protected function doRecordJobTask2(array $data)
    {
        $date = date('YmdHis', $data['ts']);
        $file_path = root_path() . "/public/csv/live/LiveUserRecord-".$date.".csv";


        if (!file_exists($file_path)) {
            $fp = fopen($file_path,'a');

            //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));

            //添加导出标题
            fputcsv($fp, ['工号', '姓名', 'Division', '部门', '学习时长(s)']);
        } else {
            $fp = fopen($file_path,'a');

            //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
        }

        $members = Db::name('temporary_members')
            ->where('type', '=', 'LiveUserRecordJobQueue')
            ->field('members_id, name, userid, openid, department_name, division')
            ->order('id', 'asc')
            ->page($data['page'], 10)
            ->select()
            ->toArray();

        $where = [];
        if (!empty($data['start']) && !empty($data['end'])) {
            $where[] = ['date', '>=', date('Ymd', strtotime($data['start']))];
            $where[] = ['date', '<=', date('Ymd', strtotime($data['end']))];
        }

        if ($members) {
            foreach($members as &$v) {
                $inf = $v;
                $count = mb_strlen($inf['userid']);
                if ($count == 6) {
                    if (is_numeric($inf['userid'])) {
                        $userid = "'00".$inf['userid'];
                    } else {
                        $userid = $inf['userid'];
                    }
                } else {
                    $userid = $inf['userid'];
                }

                $duration = Db::name('live_log')
                    ->where('userid', '=', $inf['userid'])
                    ->where($where)
                    ->sum('time');

                if (!empty($duration)) {

                    $array = [
                        $userid,
                        $inf['name'],
                        $inf['division'],
                        $inf['department_name'],
                        $duration,
                    ];

                    fputcsv($fp, $array);
                }
            }
            return ['code' => 0, 'ts' => $data['ts'], 'download_id' => $data['download_id'], 'page' => ($data['page'] + 1), 'start' => $data['start'], 'end' => $data['end']];

        } else {

            return ['code' => 1];
        }
    }
}